package account

import (
	"context"
	"database/sql"
	"module_demo/user-service/api/internal/biz"
	"module_demo/user-service/model"
	"time"

	"module_demo/user-service/api/internal/svc"
	"module_demo/user-service/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterResp, err error) {
	userModel := model.NewUserModel(l.svcCtx.Mysql)
	user, err := userModel.FindByUsername(l.ctx, req.Username)
	if err != nil {
		l.Logger.Error("查询用户失败=", err)
		return nil, biz.DBError
	}
	if user != nil {
		l.Logger.Error("用户已存在=", err)
		return nil, biz.AlreadyExistError
	}
	// 将 req.Username 转换为 sql.NullString
	username := sql.NullString{
		String: req.Username,
		Valid:  true,
	}

	_, err = userModel.Insert(l.ctx, &model.User{
		Username: username,
		Password: sql.NullString{
			String: req.Password,
			Valid:  true,
		},
		RegisterTime:  time.Now(),
		LastLoginTime: time.Now(),
	})
	if err != nil {
		l.Logger.Error("插入用户失败=", err)
		return nil, biz.DBError
	}
	return &types.RegisterResp{}, nil
}
